//
//  GoodsDetailController.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/8/16.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import WebKit
import SVProgressHUD

class GoodsDetailController: BaseViewController {
    var urlStr : String = "-999"
    
    var hiddenBar = true
    
    
    
    private var userContentController : WKUserContentController?
    
    fileprivate lazy var webView : WKWebView = {
        
        let config = WKWebViewConfiguration()
        
        let userVC = WKUserContentController()
        
        self.userContentController = userVC
        
        config.userContentController = userVC
        
        
        let webView1 = WKWebView(frame: UIScreen.main.bounds, configuration: config)
        
        
        let delegateVC = WKDelegateController()
        
        delegateVC.delegate = self
        
        webView1.uiDelegate = self
        
        config.userContentController.add(delegateVC, name: "sendMessage")
        
        webView1.navigationDelegate = self
        
        return webView1
    }()
    
    
    override func loadView() {
        
        view = webView
        
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        automaticallyAdjustsScrollViewInsets = !hiddenBar
        
        navigationController?.setNavigationBarHidden(hiddenBar, animated: true)
        
        
        
        //        1.发送请求
        if urlStr.contains("?") {
            
            if UserViewModel.shared.userIsLogin() == true {
                
                urlStr = "\(urlStr)&ios_key=\(UserViewModel.shared.key ?? "")"
            }
            
        } else {
            
            if UserViewModel.shared.userIsLogin() == true {
                
                urlStr = "\(urlStr)?ios_key=\(UserViewModel.shared.key ?? "")"
            }
            
        }
        
        
        
        let url = URL(string: urlStr)
        
        if let temp = url {
            
            
            let request = URLRequest(url: temp)
            
            webView.load(request)
            
            
        }

        

        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)
        
        webView.addObserver(self, forKeyPath: "title", options: NSKeyValueObservingOptions.new, context: nil)
        
        
        
        SVProgressHUD.show(withStatus: "正在加载数据...")
        
        
        
        
        
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        SVProgressHUD.dismiss()
    }
    
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    
    
    deinit {
        
        webView.removeObserver(self, forKeyPath: "estimatedProgress")
        webView.removeObserver(self, forKeyPath: "title")
        
        guard let temp = userContentController else {
            
            return
        }
        
        temp.removeScriptMessageHandler(forName: "sendMessage")
        
        
        QL1("------")
        
    }
    
    
}





// MARK:- KVC键值观察
extension GoodsDetailController{
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?){
        
        
//        navigationItem.title = webView.title
        
        
    }
    
    
}







extension GoodsDetailController:WKDelegateControllerDelegate,WKNavigationDelegate,WKUIDelegate{
    
    //js调用oc
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage){
        
//        QL1(message.body.self)
        
//        if message.body is Array<Any> {
//            QL1("any")
//        }
//        
//        if message.body is Array<AnyObject> {
//            QL1("anyobj")
//        }
//        
        //        if parameters[1] is String {
        //            QL1("string")
        //        }

        
        if message.body is Array<Any> {
            
            let parameters = message.body as! Array<Any>
            
            if !(parameters[0] is String) {
                
                return
            }
            
            let type = Int(parameters[0] as! String)
            
            if type == nil {
                
                return
            }
            
            if !(type! > 0) {
            
                return
            }
            
            QL1(type)
            
            //返回
            if type == 2 {
                
                navigationController?.popViewController(animated: true)
                
            }
            
            
            
            //立即购买
            if type == 3{
            
                if UserViewModel.shared.userIsLogin() == false {
                    
                    performIsLoginJump(aSelector: nil, target: nil)
                    
                } else {
                    
                    let  tempVC = BuyNowOrderVC()
                    
                    tempVC.shopInfoStr = parameters[1] as? String
                    
                    navigationController?.pushViewController(tempVC, animated: true)
                    
                }
            
               
            }
            
            
            //购物车
            if type == 4 {
                
                let temp = ShoppingCarController()
                
                navigationController?.pushViewController(temp, animated: true)
            }
            
            
            //分享
            if type == 6 {
                
                var title : String?
                var desc  : String?
                var image  : String?
                var url  : String?
                
                
                if parameters[1] is String {
                    
                    title = parameters[1] as? String
                }
                
                if parameters[2] is String {
                    desc = parameters[2] as? String
                }
                
                if parameters[3] is String {
                    image = parameters[3] as? String
                }
                
                if parameters[4] is String {
                    url = parameters[4] as? String
                }
                
                weak var weakSelf = self
                UMSocialUIManager.showShareMenuViewInWindow(platformSelectionBlock: { (platformType, userInfo) in
                    
                    switch platformType {
                    case .wechatSession:
                        weakSelf?.share(platformType: .wechatSession, title: title, desc: desc, image: image, url: url)
                    case .wechatTimeLine:
                        weakSelf?.share(platformType: .wechatTimeLine, title: title, desc: desc, image: image, url: url)
                    case .QQ:
                        weakSelf?.share(platformType: .QQ, title: title, desc: desc, image: image, url: url)
                    case .qzone:
                        weakSelf?.share(platformType: .qzone, title: title, desc: desc, image: image, url: url)
                    default:
                        weakSelf?.share(platformType: .wechatSession, title: title, desc: desc, image: image, url: url)
                    }
                    
                    
                    
                })
                
                
                
            }
            
            
            //快钱
            if type == 7{
                
                navigationController?.popViewController(animated: true)
                
                let NotifyChatMsgRecv = NSNotification.Name(rawValue:"KQDidPaySuccess")
                
                NotificationCenter.default.post(name: NotifyChatMsgRecv, object:nil)


            }

            
            
            
            //网页跳原生提现
            if type == 8{
                
                let temp = RechargeCashVC()
                
                
                temp.isMerchant = true
                
                
                navigationController?.pushViewController(temp, animated: true)
                
                
            }
            
            
            
            
            //
            if type == 10{
                
                let temp = GoodsListController()
                
                temp.keyword = parameters[1] as? String
                
                navigationController?.pushViewController(temp, animated: true)
                
                
            }

            

            
            
        }
        
    }
    
    
    
    
    
    
    
    
    
    func share(platformType : UMSocialPlatformType,title : String?,desc : String?,image : String?,url : String?) {
        
        let sharTitle = title ?? ""
        
        let sharDesc = desc ?? ""
        
        let sharImage = image ?? "http://pic.58pic.com/58pic/13/19/68/14g58PICJdQ_1024.jpg"
        
        let sharUrl = url ?? ""
        
        
        let messageObj = UMSocialMessageObject.init()
        
        let shareObj = UMShareWebpageObject.shareObject(withTitle: sharTitle, descr: sharDesc, thumImage: sharImage)
        
        shareObj?.webpageUrl = sharUrl
        
        messageObj.shareObject = shareObj
        
        
        UMSocialManager.default().share(to: platformType, messageObject: messageObj, currentViewController: self) { (resp, error) in
            
            if error == nil{
                
//                let temp = resp as? UMSocialShareResponse
                
//                QL1(temp?.message)
//                
//                QL1(temp?.originalResponse)
                
            }
            
            
        }
        
        
    }
    
    
    
    
    //发送请求前，决定是否跳转
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void){
        
        
        if navigationAction.request.url != nil {
            
            
            if navigationAction.request.url!.absoluteString.contains("mqqwpa://im/chat?") {
                
                
                if UIApplication.shared.canOpenURL(navigationAction.request.url!) {
                    
                   UIApplication.shared.openURL(navigationAction.request.url!)
                    
                }
                
                
                
            }
            
        }
      
        
        decisionHandler(.allow);
        
    }
    
    
    //页面开始加载时调用
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!){
        
        
        
        
    }
    
    
    //收到响应后，决定是否跳转
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Swift.Void){
        
        //        QL1(navigationResponse.response.url)
        
        decisionHandler(.allow);
        
        
    }
    
    
    //内容开始返回时调用
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!){
        
        
        
        
    }
    
    //OC调JS方法
    //页面加载完成后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        
        SVProgressHUD.dismiss()
        webView.evaluateJavaScript("say()") { (result, error) in
            
            //                        print(result)
            
        }
        
    }
    
    
    //页面加载失败后调用
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error){
        SVProgressHUD.dismiss()
        
        //        QL1(88888)
        
    }
    
    
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        
        let tempVC = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
        
        weak var weakSelf = self
        let action1 = UIAlertAction(title: "确定", style: .default) { (action) in
            
            completionHandler()
            
            if message.contains("请登录"){
            
                
                weakSelf?.performIsLoginJump(aSelector: nil, target: nil)
            
            }else{
            
            
               weakSelf?.navigationController?.popViewController(animated: true)
                
                //快钱支付成功操作
                
                let NotifyChatMsgRecv = NSNotification.Name(rawValue:"KQDidPaySuccess")
                
                NotificationCenter.default.post(name: NotifyChatMsgRecv, object:nil)
            
            
            }
            
            
        }
        
        
        
        let action2 = UIAlertAction(title: "取消", style: .default) { (action) in
            
            
            
        }
        
        tempVC.addAction(action2)
        tempVC.addAction(action1)
        
       present(tempVC, animated: true, completion: nil)

        
        
        
        
    }
    
    
//    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
//        
//    }
//    
//    
//    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
//        
//    }
    
    
    
    
    
    
    
    
    
}



